package com.fauks.ssm.springdata.solr;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.data.solr.core.query.Criteria;
import org.springframework.data.solr.core.query.Query;
import org.springframework.data.solr.core.query.SimpleQuery;
import org.springframework.data.solr.core.query.result.ScoredPage;

import java.util.ArrayList;
import java.util.List;

/**
 * Spring封装操作solr库
 */
public class SpringDataSolrDemo {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-solr.xml");
        SolrTemplate solrTemplate = ac.getBean("solrTemplate", SolrTemplate.class);
        //testAdd(solrTemplate);
        //testQueryById(solrTemplate);
        //testDeleteById(solrTemplate);
        //textBatchInsert(solrTemplate);
        queryByPage(solrTemplate);
    }

    //条件分页查询
    private static void queryByPage(SolrTemplate solrTemplate) {
        //创建查询对象
        Query query = new SimpleQuery("*:*");
        //开始查询的索引
        query.setOffset(0);
        //查询记录数
        query.setRows(20);
        //创建查询条件:名称包含2
        Criteria criteria = new Criteria("item_title").contains("2");
        query.addCriteria(criteria);
        ScoredPage<TbItem> tbItems = solrTemplate.queryForPage(query, TbItem.class);
        System.out.println("总记录数:" + tbItems.getSize());
        List<TbItem> content = tbItems.getContent();
        for (TbItem tbItem : content) {
            System.out.print(tbItem + "::");
        }
    }

    //批量插入数据
    private static void textBatchInsert(SolrTemplate solrTemplate) {
        List<TbItem> items = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            TbItem tbItem = new TbItem(i + 1L, "测试手机" + i, 12.5f, "", 110L, "手机", "苹果", "苹果");
            items.add(tbItem);
        }
        solrTemplate.saveBeans(items);
        solrTemplate.commit();
    }

    //按照ID删除
    private static void testDeleteById(SolrTemplate solrTemplate) {
        solrTemplate.deleteById("1");
        solrTemplate.commit();
    }

    //按照ID查询
    private static void testQueryById(SolrTemplate solrTemplate) {
        TbItem byId = solrTemplate.getById(1L, TbItem.class);
        System.out.println(byId.getSeller());
    }

    //添加一条数据
    private static void testAdd(SolrTemplate solrTemplate) {
        TbItem tbItem = new TbItem(1L, "测试手机", 12.5f, "", 110L, "手机", "苹果", "苹果");
        //更新也是使用该方法，solr会判断id相同则为更新，id不同则为新增
        solrTemplate.saveBean(tbItem);
        //保存后需要提交
        solrTemplate.commit();
    }
}
